package com.free4inno.knowledgems.controller;

import com.free4inno.knowledgems.constants.GroupConstants;
import com.free4inno.knowledgems.constants.LabelConstants;
import com.free4inno.knowledgems.dao.LabelInfoDAO;
import com.free4inno.knowledgems.domain.LabelInfo;
import com.free4inno.knowledgems.service.CleanResourceService;
import com.free4inno.knowledgems.service.LabelService;
import com.free4inno.knowledgems.constants.UserConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * LabelInfoController.
 */
@Slf4j
@Controller
@RequestMapping("/labels")
public class LabelInfoController {

    @Autowired
    private LabelInfoDAO labelInfoDao;

    @Autowired
    private CleanResourceService cleanResourceService;

    @Autowired
    private LabelService labelService;

    //    获取全部标签，平进行排列
    @ResponseBody
    @GetMapping("")
    public Map<String, Object> getLabels(HttpSession session) {
        log.info(this.getClass().getName()+"----in----"+"获取全部标签"+"----"+session.getAttribute(UserConstants.USER_ID));
        Map<String, Object> jsonObject = new HashMap<>();
        List<List<Map<String, String>>> tagList = labelService.getLabels();
        jsonObject.put(LabelConstants.CODE, 200);
        jsonObject.put(LabelConstants.MSG, "OK");
        jsonObject.put(LabelConstants.RESULT, tagList);
        log.info(this.getClass().getName()+"----out----"+"成功，返回标签列表"+"----"+session.getAttribute(UserConstants.USER_ID));
        return jsonObject;
    }

    //    增加，填入信息包含Name，Information，UplevelId
    @ResponseBody
    @PostMapping("/add")
    public Map<String, Object> newLabel(@RequestParam String labelName,
                                        @RequestParam String labelInfo,
                                        @RequestParam Integer uplevelId, HttpSession session) {
        log.info(this.getClass().getName()+"----in----"+"添加标签(add)"+"----"+session.getAttribute(UserConstants.USER_ID));

        Map<String, Object> jsonObject = new HashMap<>();

        LabelInfo label = new LabelInfo();
        label.setLabelName(labelName);
        label.setLabelInfo(labelInfo);
        label.setUplevelId(uplevelId);

        label.setCreateTime(new Timestamp(new Date().getTime()));
        label.setEditTime(new Timestamp(new Date().getTime()));
        LabelInfo saveLabel = labelInfoDao.save(label);

        jsonObject.put(LabelConstants.CODE, 200);
        jsonObject.put(LabelConstants.MSG, "OK");
        jsonObject.put(LabelConstants.RESULT, saveLabel);

        log.info(this.getClass().getName()+"----out----"+"返回添加结果"+"----"+session.getAttribute(UserConstants.USER_ID));
        return jsonObject;
    }

    //    删除，通过id查找并删除
    @ResponseBody
    @DeleteMapping("/{id}")
    public Map<String, Object> deleteLabel(@PathVariable int id, HttpSession session) {
        log.info(this.getClass().getName()+"----in----"+"通过id查找并删除"+"----"+session.getAttribute(UserConstants.USER_ID));

        Map<String, Object> jsonObject = new HashMap<>();
        labelInfoDao.deleteById(id);
        String cleanId = String.valueOf(id);
        cleanResourceService.cleanLabelIdInResource(cleanId);

        jsonObject.put(LabelConstants.CODE, 200);
        jsonObject.put(LabelConstants.MSG, "OK");
        jsonObject.put(LabelConstants.RESULT, null);
        log.info(this.getClass().getName()+"----out----"+"返回操作结果"+"----"+session.getAttribute(UserConstants.USER_ID));
        return jsonObject;
    }

    //    更改，通过id获取标签，并更改name与information
    @ResponseBody
    @PatchMapping("/{id}")
    public Map<String, Object> updateLabel(@RequestParam String labelName,
                                           @RequestParam String labelInfo,
                                           @PathVariable int id, HttpSession session) {
        log.info(this.getClass().getName()+"----in----"+"通过id查找并更新"+"----"+session.getAttribute(UserConstants.USER_ID));

        Map<String, Object> jsonObject = new HashMap<>();

        try {
            LabelInfo label = labelInfoDao.findById(id).orElseThrow(() -> new LabelNotFoundException(id, session));
            label.setLabelName(labelName);
            label.setLabelInfo(labelInfo);
            label.setEditTime(new Timestamp(new Date().getTime()));
            LabelInfo updateLabel = labelInfoDao.save(label);

            jsonObject.put(LabelConstants.CODE, 200);
            jsonObject.put(LabelConstants.MSG, "OK");
            jsonObject.put(LabelConstants.RESULT, updateLabel);
            log.info(this.getClass().getName()+"----out----"+"修改成功，返回结果"+"----"+session.getAttribute(UserConstants.USER_ID));
            return jsonObject;
        } catch (LabelNotFoundException e) {
            jsonObject.put(LabelConstants.CODE, 500);
            jsonObject.put(LabelConstants.MSG, e.getMessage());
            jsonObject.put(LabelConstants.RESULT, null);
            log.info(this.getClass().getName()+"----out----"+"修改失败，根据id没有找到标签"+"----"+session.getAttribute(UserConstants.USER_ID));
            return jsonObject;
        }
    }

    //    带着参数跳转到分类页面
    @RequestMapping("/labels")
    public String getUserInfo(Map param, @RequestParam("id") String labelId, HttpSession session) {
        log.info(this.getClass().getName()+"----in----" + "分类标签(labels)" + "----" + session.getAttribute(UserConstants.USER_ID));
//        String labelId = "";
//        List<LabelInfo> labelInfos = labelInfoDao.findAll();
//        for (LabelInfo labelInfo : labelInfos) {
//            if (labelInfo.getLabelName().equals(labelName)) {
//                labelId = labelInfo.getId().toString();
//            }
//        }
        param.put("label_id", labelId);
        log.info(this.getClass().getName()+"----out----" + "带着参数跳转到分类页面" + "----" + session.getAttribute(UserConstants.USER_ID));
        return "label/labels";
    }

    //    获取labelManage.jsp页面
    @GetMapping("/labelManage")
    public String showLabelManagePage(HttpSession session) {
        log.info(this.getClass().getName()+"----in----" + "分类标签管理(labels)" + "----" + session.getAttribute(UserConstants.USER_ID));
        if (session.getAttribute(GroupConstants.ROLE_ID).equals(1) || session.getAttribute(GroupConstants.ROLE_ID).equals(3)) {
            log.info(this.getClass().getName()+"----out----" + "用户具有权限，跳转标签管理页面" + "----" + session.getAttribute(UserConstants.USER_ID));
            return "label/labelmanage";
        } else {
            log.info(this.getClass().getName()+"----out----" + "用户不具有权限, 重定向到首页" + "----" + session.getAttribute(UserConstants.USER_ID));
            return "redirect:/";
        }
    }

    static class LabelNotFoundException extends RuntimeException {
        LabelNotFoundException(Integer id, HttpSession session) {
            super("Not found label info " + id);
            log.error(this.getClass().getName()+"----" + "find label by id" + "----failure----" + "Not found label info " + id + "----"+session.getAttribute(UserConstants.USER_ID));
        }
    }
}
